//
//  OAuthViewController.swift
//  sinazd
//
//  Created by apple on 16/3/7.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {

    
    let webView = UIWebView()
    
    @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func defaultAccount() {
        //需要在webView中 设置账号和密码
        let jsString = "document.getElementById('userId').value = '18769487960', document.getElementById('passwd').value = '8866zhang' "
        //通过字符串来执行javascrip 代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    private func setNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultAccount")
        
    }
    
    
    //解决 选择关闭选项时，hud不消失的bug
    override func viewWillDisappear(animated: Bool) {
        
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    
    //重写此方法，把uiview换成uiwebview
    override func loadView() {
        view = webView
        
        webView.opaque = false
        
        webView.delegate = self
        
        
    }
    
    //授权加载界面
    private func loadOauthPage(){
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)"  + "&redirect_uri=\(redirect_uri)"
        
        let url = NSURL(string: urlStr)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    
    
    //重写此方法，设置view的背景色，并设置navigationBar
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        
        setNav()
        
        view.backgroundColor = UIColor.whiteColor()
        
        loadOauthPage()
        
    }
    
}


//webview协议方法
extension OAuthViewController:UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //获取code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlStr = request.URL?.absoluteString else {
            return false
        }
        
        print(urlStr)
        
        if urlStr.containsString("code") {
            
            //在这个地方获取code= 后面的字符串 通过它获得token
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
          
        print("11111111111111111111111111")
            print(query,code)
       print("11111111111111111111111111")

            
           UserAccount.sharedAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
            
            if !isSuccess{
                SVProgressHUD.showErrorWithStatus("没网了，别着急")
                return 
            }
         
            self.close()
            
            NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            
           })
            
            return false
            
        }
        return true
    }
    
}
